<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/8/23
 * Time: 17:29
 * 权限控制
 */

namespace app\index\controller;
use app\Base as parentBase;
use app\common\model\CenterModel;

class Base extends parentBase
{
    public function __construct (){
        parent::__construct();
        $this->center_info = empty(session("center_info")) ? '' : session("center_info") ;
        define('CID',empty($this->center_info) ? 0 : $this->center_info['id']);
        $this->assign('center_info',$this->center_info);
        $this->assign('title','Sea社区');

    }

    public function isLogin()
    {
        if( !CID ){
            $this->redirect('/index/base/login');
        }

    }

    //登入
    public function login()
    {
        if( request()->isPost() ){
            $param = input("param.");
            $validate = new \think\Validate([
                ['__token__','require|token','来路错误|请勿重复提交'],
                ['username', 'require', '用户名不能为空'],
                ['password', 'require', '密码不能为空'],
            ]);
            if(!$validate->check($param)){
                request()->token();
                $this->error('登陆失败');
            }
            $center = new CenterModel();
            $param['password'] = md5($param['password'] . config('salt'));
            $where['username'] = $param['username'];
            $where['password'] = $param['password'];
            $login_info =  $center->getOneCenter($where);
            $login_info = json_decode($login_info,true);

            if(empty($login_info)){
                $this->error('用户名或者密码错误');
            }
            if($login_info['disabled'] != '1'){
                $this->error('账号处于禁用状态,请联系网站管理员');
            }

            $center->incLoginNum($where);

            session('center_info',$login_info);

            $this->success('登陆成功','forum/index');
        }

        return $this->fetch();
    }

    //注册
    public function reg()
    {
        if (request()->isPost()) {
            $param = input("param.");
            $center = new CenterModel();
            $result = $center->insertCenter($param);
            if ($result['code'] == 1) {
                $center->incLoginNum(['username' => $param['username']]);
                $this->success($result['msg'], $result['data']);
            } else {
                $this->error($result['msg']);
            }

        }
        return $this->fetch();
    }


    /**
     * 退出登录
     */
    public function logout(){
        session('center_info',null);
        $this->success('退出登陆成功','/index/forum');
    }

}